//
//  KKTextView.m
//  KKDoctor
//
//  Created by Mac mini on 15/10/29.
//  Copyright © 2015年 KKiHeng. All rights reserved.
//

#import "KKTextView.h"

@interface KKTextView() {
    
    UILabel *_placeholderLabel;
}

@end

@implementation KKTextView

static CGFloat placeholderOffset = 10;

- (void)setPlaceholder:(NSString *)placeholder {
    
    if (_placeholderLabel == nil) {
        _placeholderLabel = [[UILabel alloc] initWithFrame: CGRectMake(placeholderOffset, placeholderOffset, CGRectGetWidth(self.bounds) - placeholderOffset * 2, 20)];
        _placeholderLabel.backgroundColor = [UIColor clearColor];
        _placeholderLabel.userInteractionEnabled = false;
        _placeholderLabel.textColor = [UIColor colorWithWhite:0.85 alpha:1.000];
        _placeholderLabel.text = placeholder;
        _placeholderLabel.autoresizingMask = UIViewAutoresizingFlexibleWidth;
        _placeholderLabel.font = self.font;
        [self addSubview: _placeholderLabel];
        
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(listenTextView:) name:UITextViewTextDidBeginEditingNotification object: self];
        [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(listenTextView:) name:UITextViewTextDidEndEditingNotification object: self];
        
        self.textContainerInset = UIEdgeInsetsMake(placeholderOffset, placeholderOffset, placeholderOffset, placeholderOffset);
    }
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver: self];
}

#pragma mark NSNotification methods

- (void)listenTextView:(NSNotification*)notification {
    
    if (notification.object != self) {
        return;
    }
    
    if ([notification.name isEqualToString: UITextViewTextDidBeginEditingNotification]) {
        _placeholderLabel.hidden = true;
    }
    else if ([notification.name isEqualToString: UITextViewTextDidEndEditingNotification]) {
        _placeholderLabel.hidden = self.text.length ? true : false;
    }
}

@end
